package mnc.game.tifo;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

public class DataCommunication {

	String errorCode    = "";
	String errorMessage = "";
	private int size1 = 0;
	
	static HttpClient httpClientInstance = null;
	
	public static HttpClient getHttpClientInstance() {
		if(httpClientInstance == null)
			httpClientInstance = new DefaultHttpClient();
		
		return httpClientInstance;
	}
	
	public HttpClient getHttpClient()
	{
		return getHttpClientInstance();
	}
	
	public void shutdown() {
		getHttpClient().getConnectionManager().shutdown();
	}

	/**
	 * Send data without Bitmap Image 1111
	 * @param CMD
	 * @param ACT
	 * @param data_map
	 * @return
	 */
	public ArrayList<HashMap<String, String>> sendData(String surl, ArrayList<HashMap<String, String>> param)
	{
		ArrayList<HashMap<String, String>> return_data = null;
		try {
			// HttpPost 생성

//			HttpPost post = new HttpPost(Constant.SERVER_URL + surl);
		    System.out.println("122");
			URL url = new URL( surl);
			
			// HttpPost Header Setting
		    HttpClient httpclient = getHttpClient();
		    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000);
		    HttpConnectionParams.setSoTimeout(httpclient.getParams(), 25000);
		    HttpURLConnection httpURLCon = (HttpURLConnection)url.openConnection();
		    
		    httpURLCon.setDefaultUseCaches(false);
		    httpURLCon.setDoInput(true);
		    httpURLCon.setDoOutput(true);
		    httpURLCon.setRequestMethod("POST");
		    httpURLCon.setRequestProperty("content-type", "application/x-www-form-urlencoded");
		    System.out.println("1110");
			// Parameter Setting
		    StringBuffer sb = new StringBuffer();
		    for(int i = 0; i < param.size(); i++) {
		    	HashMap mp = param.get(i);
				Set set = mp.entrySet();
				Iterator it = set.iterator();
	
				while(it.hasNext())
				{
					Map.Entry m = (Map.Entry)it.next();				
					String key = (String) m.getKey();				
					System.out.println(key);
					String value = (String) m.getValue();
					System.out.println(key + " --- " + value);
			    	
					sb.append(key).append("=").append(value).append("&");
				}				
		    }
		    System.out.println("1111");

		    StringBuilder sbb = new StringBuilder();
			if(sb.toString().length() > 0) sbb.append(sb.toString().substring(0,sb.toString().length()-1));

		    PrintWriter pw = new PrintWriter(new OutputStreamWriter(httpURLCon.getOutputStream(), "UTF-8"));
		    pw.write(sbb.toString());
		    pw.flush();
		    
		    System.out.println("1112");
		
			return_data = parsingJSONData(httpURLCon);		    
			// Connection Shutdown
		    httpclient.getConnectionManager().shutdown();
		} catch(ConnectTimeoutException e1) {
			System.out.println(e1);
			return_data = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", "HTTP-ERR");
			map.put("ERR_MSG",  "서버 접근이 되지 않습니다");
			return_data.add(map);				
		} catch(SocketTimeoutException e1) {
			System.out.println(e1);
			return_data = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", "HTTP-ERR");
			map.put("ERR_MSG",  "TimeOut이 발생 했습니다");
			return_data.add(map);		    
		} catch(Exception e) {
			System.out.println(e);
			return_data = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", "HTTP-ERR");
			map.put("ERR_MSG", e+"");
			return_data.add(map);
		}

		

		return return_data;
	}	

	/**
	 * parsing HashMap data to JSON format String
	 * @param data
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private String parsingHashMapToJSONString(HashMap<String, String> data)
	{
		String request_data = "{";
		
		Set set = data.entrySet();
		Iterator it = set.iterator();

		while(it.hasNext())
		{
			if(request_data.equals("{") == false)
				request_data += ",";
			
			Map.Entry m = (Map.Entry)it.next();				
			String key = (String) m.getKey();				
			String value = (String) m.getValue();

			request_data += "\"" + key + "\":\"" + value + "\"";
		}
		
		request_data += "}";
		
		return request_data;
	}


	private ArrayList<HashMap<String, String>> parsingJSONData(HttpURLConnection httpURLCon)
	{
		ArrayList<HashMap<String, String>> return_data = new ArrayList<HashMap<String,String>>();

		String line;
		
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = null;
		InputStreamReader isr = null;
		JSONObject json;
		
		try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(httpURLCon.getInputStream(), "UTF-8"));
            while((line = bf.readLine()) != null) {
            	builder.append(line);
            }
			
			
			String json_str = builder.toString();
			if(json_str.equals("") || json_str.equals("null") || json_str == null)
				return return_data;
			Log.i("json_str",json_str);
			json = new JSONObject(json_str);
			// error 부분
			errorCode = json.getString("resultcode");
			errorMessage = json.getString("resultmsg");
			String jobType = json.getString("jobType");
			System.out.println("jobType = " + jobType);
			
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", errorCode);
			map.put("ERR_MSG", errorMessage);
			if(jobType.equals("3")) {
				map.put("notice",  json.getString("notice"));
			} else if(jobType.equals("2")) {
				map.put("TOTAL_NUM",  json.getString("TOTAL_NUM"));
				map.put("GAME_NUM",  json.getString("GAME_NUM"));
				map.put("HART_NUM",  json.getString("HART_NUM"));
				map.put("STAGE",  json.getString("STAGE"));
				map.put("TIFO_COUNT",  json.getString("TIFO_COUNT"));
				map.put("USER_TIME",  json.getString("USER_TIME"));
			} else if(jobType.equals("7")) {
				map.put("VERSION",  json.getString("VERSION"));
			}
			
			return_data.add(map);	


 			
			// Formatted COMMON & BODY
//			if(json.isNull("rows") == false)
//			{
//				JSONArray body = json.getJSONArray("rows");				
//				jsonArrayToArrayListHashMap(body, return_data);
//			}

		} catch (RuntimeException e) {
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", "900");
			map.put("ERR_MSG", "데이터 범위가 너무 큽니다");
			return_data.add(map);	
		} catch (Exception e) {
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", "900");
			map.put("ERR_MSG", e.toString());
			e.printStackTrace();
			return_data.add(map);	

		} finally {
			try {
				if(isr != null) isr.close();
				if(reader != null) reader.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return return_data;
	}	
	/**
	 * Parsing HttpEntity to ArrayList<HashMap<String, String>>
	 * @param entity HttpEntity
	 * @return ArrayList<HashMap<String, String>>
	 */
	private ArrayList<HashMap<String, String>> parsingJSONData(HttpURLConnection httpURLCon, String key)
	{
		ArrayList<HashMap<String, String>> return_data = new ArrayList<HashMap<String,String>>();

		String line;
		
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = null;
		InputStreamReader isr = null;
		JSONObject json;
		
		try {
			
            BufferedReader bf = new BufferedReader(new InputStreamReader(httpURLCon.getInputStream(), "UTF-8"));
            while((line = bf.readLine()) != null) {
            	builder.append(line);
            }
			
			Log.i("builder",builder.toString());
			String json_str = builder.toString();
			if(json_str.equals("") || json_str.equals("null") || json_str == null)
				return return_data;
			
			Log.i("json_str", json_str);
			json = new JSONObject(json_str);
			// error 부분
			errorCode = json.getString("errorCode");
			errorMessage = json.getString("errorMessage");
			
			HashMap<String, String> map = new HashMap();
			System.out.println("err = " + errorCode + " errorMessage = " + errorMessage);
			map.put("ERR_CODE", errorCode);
			map.put("ERR_MSG", errorMessage); 
//			if(errorCode.equals("0")) {
				String nodeName[] = key.split(",");
				for(int i = 0; i < nodeName.length; i++) {
					try {
						map.put(nodeName[i], json.getString(nodeName[i])); 
					} catch(JSONException e) {
						map.put(nodeName[i], ""); 
					}
				}
//			}

			return_data.add(map);	

			
			// Formatted COMMON & BODY
			if(json.isNull("rows") == false)
			{
				
				// parsing JSONArray
//				JSONArray head = json.getJSONArray("tables");
//				JSONObject json1 = new JSONObject(jsonArrayToString(head));
				
				JSONArray body = json.getJSONArray("rows");				
				jsonArrayToArrayListHashMap(body, return_data);
			}


		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
//		} catch (JSONException e) {
//			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(isr != null) isr.close();
				if(reader != null) reader.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return return_data;
	}	


	private ArrayList<HashMap<String, String>> parsingJSONDataBank(HttpURLConnection httpURLCon, String key)
	{
		ArrayList<HashMap<String, String>> return_data = new ArrayList<HashMap<String,String>>();

		String line;
		
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = null;
		InputStreamReader isr = null;
		JSONObject json;
		
		try {
			
            BufferedReader bf = new BufferedReader(new InputStreamReader(httpURLCon.getInputStream(), "UTF-8"));
            while((line = bf.readLine()) != null) {
            	builder.append(line);
            }
			
			String json_str = builder.toString();
			if(json_str.equals("") || json_str.equals("null") || json_str == null)
				return return_data;
			
			Log.i("json_str", json_str);
			json = new JSONObject(json_str);
			// error 부분
			errorCode = json.getString("errorCode");
			errorMessage = json.getString("errorMessage");
			
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", errorCode);
			map.put("ERR_MSG", errorMessage); 
			String nodeName[] = key.split(",");
			for(int i = 0; i < nodeName.length; i++) {
				try {
					map.put(nodeName[i], json.getString(nodeName[i])); 
				} catch(JSONException e) {
					map.put(nodeName[i], ""); 
				}
			}
			return_data.add(map);	
			
			if(json.isNull("rows") == false)
			{
				
				// parsing JSONArray
//				JSONArray head = json.getJSONArray("tables");
//				JSONObject json1 = new JSONObject(jsonArrayToString(head));
				
				JSONArray body = json.getJSONArray("rows");				
				jsonArrayToArrayListHashMap(body, return_data);
				
				size1 = return_data.size();
			}
			if(json.isNull("banks") == false)
			{
				System.out.println("11112");
				JSONArray body1 = json.getJSONArray("banks");				
				jsonArrayToArrayListHashMap(body1, return_data);
				System.out.println("size22 = " +  return_data.size());
				
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(isr != null) isr.close();
				if(reader != null) reader.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return return_data;
	}	
	/**
	 * Parsing HttpEntity to ArrayList<HashMap<String, String>>
	 * @param entity HttpEntity
	 * @return ArrayList<HashMap<String, String>>
	 */
	private ArrayList<HashMap<String, String>> parsingJSONData(String json_str, String key)
	{
		ArrayList<HashMap<String, String>> return_data = new ArrayList<HashMap<String,String>>();

		JSONObject json;
		
		try {
			if(json_str.equals("") || json_str.equals("null") || json_str == null)
				return return_data;
			
			json = new JSONObject(json_str);
			// error 부분
			errorCode = json.getString("errorCode");
			errorMessage = json.getString("errorMessage");
			
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", errorCode);
			map.put("ERR_MSG", errorMessage);
			
			return_data.add(map);	

			
			// Formatted COMMON & BODY
			if(json.isNull("tables") == false)
			{
				
				// parsing JSONArray
				JSONArray head = json.getJSONArray("tables");
				JSONObject json1 = new JSONObject(jsonMultiArray(head, key));
				
				JSONArray body = json1.getJSONArray("rows");				
				jsonArrayToArrayListHashMap(body, return_data);			

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return return_data;
	}
	/**
	 * Parsing HttpEntity to ArrayList<HashMap<String, String>>
	 * @param entity HttpEntity
	 * @return ArrayList<HashMap<String, String>>
	 */
	private ArrayList<HashMap<String, String>> parsingJSONData(String json_str, String key, String nodeName)
	{
		ArrayList<HashMap<String, String>> return_data = new ArrayList<HashMap<String,String>>();

		JSONObject json;
		
		try {
			if(json_str.equals("") || json_str.equals("null") || json_str == null)
				return return_data;
			
			json = new JSONObject(json_str);
			// error 부분
			errorCode = json.getString("errorCode");
			errorMessage = json.getString("errorMessage");
			
			HashMap<String, String> map = new HashMap();
			map.put("ERR_CODE", errorCode);
			map.put("ERR_MSG", errorMessage);
			map.put(nodeName, json.getString(nodeName)); 
			return_data.add(map);	

			
			// Formatted COMMON & BODY
			if(json.isNull("tables") == false)
			{
				
				// parsing JSONArray
				JSONArray head = json.getJSONArray("tables");
				JSONObject json1 = new JSONObject(jsonMultiArray(head, key));
				
				JSONArray body = json1.getJSONArray("rows");				
				jsonArrayToArrayListHashMap(body, return_data);			

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return return_data;
	}
	/**
	 * Parsing JSONObject to HashMap<String, String>
	 * @param json JSONObject
	 * @return HashMap<String, String>
	 */
	private HashMap<String, String> jsonToHashMap(JSONObject json)
	{
		HashMap<String, String> data = new HashMap<String, String>();
		
		@SuppressWarnings("unchecked")
		Iterator<String> i = json.keys();
		
		while(i.hasNext())
		{
			String next = i.next(); 
			String value = "";
			try {
				value = json.getString(next);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			data.put(next, value);
		}
		
		return data;
	}

	/**
	 * Parsing JSONArray to ArrayList<HashMap<String, String>>  
	 * @param jsonArray JSONArray
	 * @return ArrayList<HashMap<String, String>>
	 */
	private void jsonArrayToArrayListHashMap(JSONArray jsonArray, ArrayList<HashMap<String, String>> data_array)
	{
		try 
		{
			if(jsonArray.length() == 0) {
				data_array.remove(0);
				HashMap<String, String> map = new HashMap();
				map.put("ERR_CODE", "NO-DATA");
				map.put("ERR_MSG", "데이터가 없습니다");
				data_array.add(map);	
			}
			for(int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject item = jsonArray.getJSONObject(i);
				
				HashMap<String, String> data = new HashMap<String, String>();	
				
				@SuppressWarnings("unchecked")
				Iterator<String> itr = item.keys();
								
				while(itr.hasNext())
				{

					String next = itr.next(); 
					String value = item.getString(next);
					data.put(next, value);	
				}
				
				data_array.add(data);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private String jsonArrayToString(JSONArray jsonArray)
	{
		StringBuffer data = new StringBuffer();
		data.append("{\"rows\":");	
		try 
		{
			for(int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject item = jsonArray.getJSONObject(i);
				
				@SuppressWarnings("unchecked")
				Iterator<String> itr = item.keys();
								
				while(itr.hasNext())
				{
					String next = itr.next(); 
					if(next.equals("rows")) {
						String value = item.getString(next);
						
						data.append(value);	
					}
	
				}
				
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		data.append("}");
		return data.toString();

	}
	
	private String jsonMultiArray(JSONArray jsonArray, String key)
	{
		StringBuffer data = new StringBuffer();
		boolean id = false;
		boolean idVal = false;
		data.append("{\"rows\":");	
		try 
		{
			for(int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject item = jsonArray.getJSONObject(i);
				
				@SuppressWarnings("unchecked")
				Iterator<String> itr = item.keys();
								
				while(itr.hasNext())
				{
					String next = itr.next(); 
					if(next.equals("id")) {
						id = true;
						String val = item.getString(next);
						if(val.equals(key)) {
							idVal = true;
						} else {
							idVal = false;
						}
					}
					if(next.equals("rows") && id && idVal) {
						String value = item.getString(next);
						
						data.append(value);	
					}
				}
				
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		data.append("}");
		return data.toString();

	}	
	/**
	 * byte[] -> bitmap
	 * @param b
	 * @return bitmap
	 */
	@SuppressWarnings("unused")
	private Bitmap byteToBitmap(byte[] b)
	{
		Bitmap bitmap = null;
		bitmap = BitmapFactory.decodeByteArray( b, 0, b.length ) ;
		return bitmap;
	}
	
	/**
	 * bitmap -> byte[]
	 * @param bitmap
	 * @return byte[]
	 */
	private byte[] bitmapToByte(Bitmap bitmap)
	{
		ByteArrayOutputStream  byteArray = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, byteArray);
		byte[] b = byteArray.toByteArray();
		
		return b;
	}
	
	/** byte[] -> String 
	 * @param $byte
	 * @return String
	 */
	public static String byteToString( byte[] $byte ) {
		String result = EncodingUtils.getString( $byte, 0, $byte.length, "Latin-1") ;
		return result ;
	}
	
	/**
	 * String -> byte[]
	 * @param $byteString
	 * @return byte[]
	 */
	public static byte[] stringToByte( String $byteString ) {
		byte[] byteArray = EncodingUtils.getBytes($byteString, "Latin-1") ;
		return byteArray ;
	}
}
